package org.yray.ttmq;


import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.HexUtils;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * MQTT处理器
 * @author
 */
@Component
@Slf4j
public class MqttHandle implements MqttCallback {
    private static RandomAccessFile f;

    static
    {
        try {
            f=new RandomAccessFile(new File("D://r"),"rws");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /** 日志组件 */
    // private static Logger log = LoggerFactory.getLogger(MqttHandle.class);

    /**
     * 连接丢失
     * @param cause
     */
    @Override
    public void connectionLost(Throwable cause) {
        System.out.println("connection lost：" + cause.getMessage());
        MqttInitialized.reconnection();
    }

    /**
     * 收到消息
     * @param topic
     * @param message
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        log.info("订阅消息已收到...");
        System.out.println("topic:" + topic);
        System.out.println("Qos:" + HexUtils.toHexString(message.getPayload()));
        try {

                f.write(message.getPayload());


        } catch (Exception e) {
            e.printStackTrace();
        }
        // System.out.println("Received message: \n  topic：" + topic + "\n  Qos：" + message.getQos() + "\n  payload：" + new String(message.getPayload()));
    }

    /**
     * 消息传递成功
     * @param token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }

}

